(function () {
    var checkAll = document.getElementById('checkAll')
    var tbody = document.querySelectorAll('tbody')[0]
    var firstCheckAll = tbody.querySelectorAll('input')
    var ths = document.querySelectorAll('th')   // th集合
    console.log(ths);
    var rows = tbody.querySelectorAll('tr')     // 所有的行的集合

    function init() {
        checkAll.addEventListener('click', checkAllFn) //全选按钮处理
        firstCheckAll.forEach(function (item) {
            item.addEventListener('click', firstCheckAllFn)
        }) //单选处理
        ths.forEach(function (node, index) {
            node.addEventListener('click', onThsClick(node, index))
          })
    }




    function onThsClick(node, index) {
        console.log(index);
        if (index === 0) return
        node.addEventListener('click', function () {
            var arr = Array.prototype.slice.apply(rows)
            arr.sort(function (a, b) {
                if (index === 2 || index === 4) {
                    return  a.querySelectorAll('td')[index].innerHTML.localeCompare(b.querySelectorAll('td')[index].innerHTML,'zh')
                } else {
                    return  a.querySelectorAll('td')[index].innerHTML - b.querySelectorAll('td')[index].innerHTML
                }
            })
            console.log(arr);
            arr.forEach(function (node) {
                tbody.appendChild(node)
            })
       })
    }

    function firstCheckAllFn() {
        var checkNum = 0
        firstCheckAll.forEach(item => {
            item.checked && ++checkNum
        })
        checkAll.checked = checkNum === firstCheckAll.length
    }

    function checkAllFn(e) {
        var status = this.checked
        for (var i = 0; i < firstCheckAll.length; i++) {
            firstCheckAll[i].checked = status
        }
    }

    init()

})()